package com.pengcheng.hnweb.config;

import com.pengcheng.hnweb.listener.RedisKeyExpiredListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
@Slf4j
public class RedisConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisKeyExpiredListener redisKeyExpiredListener;

    @Value("${spring.redis.database}")
    private int redis_database;
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisTemplate.getConnectionFactory());
        // 配置监听的 Redis Key 过期事件的频道
        container.addMessageListener(redisKeyExpiredListener, new PatternTopic("__keyevent@"+redis_database+"__:expired"));
        log.info("__keyevent@"+redis_database+"__:expired");
        return container;
    }
}
